//
//  main.cpp
//  MyClient
//
//  Created by RJ G on 2025/5/1.
//

#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "FileUtiles.h"

const int PORT = 8080;
const char* SERVER_IP = "127.0.0.1";
const int BUFFER_SIZE = 1024;
int g_server;

void receiveFile();

int main() {
    // 创建socket
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0) {
        std::cerr << "Socket创建失败" << std::endl;
        return 1;
    }

    // 连接服务器
    sockaddr_in serv_addr;
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(PORT);
    
    if (inet_pton(AF_INET, SERVER_IP, &serv_addr.sin_addr) <= 0) {
        std::cerr << "无效地址/地址不支持" << std::endl;
        return 1;
    }

    if (connect(sock, (sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
        std::cerr << "连接失败" << std::endl;
        return 1;
    }
    g_server = sock;
    std::string temp;

    while (true) {
        char buffer[BUFFER_SIZE] = {0};
        read(sock, buffer, BUFFER_SIZE);
        if (!strcmp(buffer, "exit")) {
            break;
        }
        std::cout << "收到响应: " << buffer << std::endl;
        temp = buffer;
        if (temp == "start to transport file") {
            receiveFile();
            temp = "received.txt";
            readUTF8File(temp);
            temp = "文件接收完成";
            send(sock, temp.c_str(), temp.size(), 0);
            continue;
        }
        if (temp.find("ask:") != std::string::npos) {
            generateArtical(temp);
            temp = "还有要问的吗？";
            send(sock, temp.c_str(), temp.size(), 0);
            continue;
        }
        
        std::string message = "Hello from client";
        getline(std::cin, message);
        if (message == "exit" || message.size() == 0) {
            break;
        }
        send(sock, message.c_str(), message.size(), 0);
        std::cout << "已发送消息" << std::endl;
    }

    // 关闭连接
    close(sock);
    return 0;
}
